﻿using System;
using System.Linq;
using System.Web.UI.WebControls;
using System.Data;
using Business;
using System.Web.Security;
using DataAccess;

public partial class admin_Create_Report : System.Web.UI.Page
{
    Decryption objdec = new Decryption();
    i2iPortalLinqToSQLDataContext dataContext = new i2iPortalLinqToSQLDataContext();

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            var query_client = "select * from clients";
            var conobj2 = new CreateConn();
            var cdt = conobj2.SQLConnDataTable(query_client);
            string clientName;

            foreach (DataRow client in cdt.Rows)
            {
                clientName = client["clientName"].ToString();
                var parentID = client["parent_client_id"];
                if (parentID != DBNull.Value && Int32.Parse(parentID.ToString()) != 0)
                {
                    continue;
                }
                else if (clientName.Equals("Administrator"))
                {
                    continue;
                }

                var clientid = client["client_id"].ToString();
                var clienitem = new ListItem(clientName, clientid, true);
                Selectclient_DropDownList1.Items.Add(clienitem);
            }
            var clientid2 = Int32.Parse(Selectclient_DropDownList1.SelectedValue);
            var STA = new DataAccess.i2iPortalTableAdapters.SitesTableAdapter();
            var query_areas = "select * FROM clients where parent_client_id='" + clientid2 + "'";
            var conobj = new CreateConn();
            var dt = conobj.SQLConnDataTable(query_areas);
            if (dt != null && dt.Rows.Count > 0)
            {
                foreach (DataRow dr in dt.Rows)
                {
                    var area_name = dr["clientName"].ToString();
                    var area_id = dr["client_id"].ToString();
                    var areitem = new ListItem(area_name, area_id, true);
                    AreaDropDownList.Items.Add(areitem);
                }
            }
            else
            {
                AreaDropDownList.Items.Add(Selectclient_DropDownList1.SelectedItem);
            }
            var sitesitems = AreaDropDownList.Items.GetEnumerator();
            if (sitesitems.MoveNext())
            {
                var siteitem = (ListItem) sitesitems.Current;
                var sites_clientID = Int32.Parse((siteitem.Value));
                DataTable st = STA.GetDataByClientID(sites_clientID);
                foreach (DataRow site in st.Rows)
                {
                    var siteName = site["siteName"].ToString();
                    var siteid = site["site_id"].ToString();

                    var site_CB = new CheckBox();
                    site_CB.Text = siteName;
                    site_CB.ID = siteid;
                    SitesCheckBoxList.Items.Add(siteName);
                }
            }
            setDateList();
        }
    }

    protected void FormViewReport_DataBound(object sender, EventArgs e)
    {
    }

    protected String GetComment(string comment_id)
    {
        var objcon = new CreateConn();
        var query = "SELECT commentDescription FROM StandardComments" +
            " WHERE comment_id = " + comment_id;
        var dt = objcon.SQLConnDataTable(query);
        var comment = dt.Rows[0]["commentDescription"].ToString();

        return comment;
    }

    public void setDateList()
    {
        int selectedSite;
        DateDropdownList.Items.Clear();
        if (Int32.TryParse(AreaDropDownList.SelectedValue.ToString(), out selectedSite))
        {
            var queryReportDates = (from cs in dataContext.ComponentStatus
                join c in dataContext.Components on cs.component_id equals c.component_id
                join m in dataContext.Machines on c.machine_id equals m.machine_id
                join s in dataContext.Sites on m.site_id equals s.site_id
                where s.client_id == selectedSite
                select cs).Select(cs => cs.dateRecorded).Distinct().ToArray().OrderByDescending(cs => cs.Date);

            foreach (var dr in queryReportDates)
            {
                var dateitem = new ListItem(dr.ToString("dd/MM/yyyy"), dr.ToString("dd/MM/yyyy"));
                DateDropdownList.Items.Add(dateitem);
            }
        }
    }

    /// <summary>
    /// Handles the Click event of the InsertCancelButton control.
    /// Go to the source page
    /// </summary>
    /// <param name="sender">The source of the event.</param>
    /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
    protected void InsertCancelButton_Click(object sender, EventArgs e)
    {
        var component_id = "";
        try
        {
            component_id = objdec.DecodeUrl(Request.QueryString["component_id"].ToString());
        }
        catch (Exception err)
        {
            Console.Write("Err msg:" + err.Message);
        }
        if (component_id != "")
        {
            Server.Transfer("View_Comp.aspx?component_id=" + component_id);
        }
        else
        {
            Server.Transfer("Mng_Report.aspx");
        }
    }

    protected void Client_changed(object sender, EventArgs e)
    {
        SitesCheckBoxList.Items.Clear();
        AreaDropDownList.Items.Clear();
        var clientid = Int32.Parse(Selectclient_DropDownList1.SelectedValue);
        var STA = new DataAccess.i2iPortalTableAdapters.SitesTableAdapter();
        var query_areas = "select * FROM clients where parent_client_id='"+clientid+"'";
        var conobj = new CreateConn();
        var dt =  conobj.SQLConnDataTable(query_areas);
        if (dt != null && dt.Rows.Count > 0)
        {
            AreaDropDownList.Items.Clear();
            foreach (DataRow dr in dt.Rows)
            {
                var area_name = dr["clientName"].ToString();
                var area_id = dr["client_id"].ToString();
                var areitem = new ListItem(area_name,area_id,true);
                AreaDropDownList.Items.Add(areitem);
            }
        }
        else
        {
            AreaDropDownList.Items.Add(Selectclient_DropDownList1.SelectedItem);
       
        }
        var sitesitems = AreaDropDownList.Items.GetEnumerator();
        if (sitesitems.MoveNext())
        {
            var siteitem = (ListItem)sitesitems.Current;
            var sites_clientID = Int32.Parse((siteitem.Value));
            DataTable st = STA.GetDataByClientID(sites_clientID);
            foreach (DataRow site in st.Rows)
            {
                var siteName = site["siteName"].ToString();
                var siteid = site["site_id"].ToString();

                var site_CB = new CheckBox();
                site_CB.Text = siteName;
                site_CB.ID = siteid;
                SitesCheckBoxList.Items.Add(siteName);
            }
            setDateList();
        }
    }

    public void on_Button_submitClicked(object sender, EventArgs e)
    {
        Response.Redirect("Create_Report2.aspx");
    }

    protected void submit_button_Click(object sender, EventArgs e)
    {
        var clientid = Selectclient_DropDownList1.SelectedValue;
        var clientname = Selectclient_DropDownList1.SelectedItem.Text;
        Session["clientid"] = clientid;
        Session["clientname"] = clientname;
        string[] selectedsites = null;

        var i = 0;
        foreach (ListItem lt in SitesCheckBoxList.Items)
        {
            if (lt.Selected)
            {
                i = i + 1;//Get the count of selected sites
            }

        }
        var j = 0;
        selectedsites = new string[i];
        foreach (ListItem lt in SitesCheckBoxList.Items)
        {

            if (lt.Selected)
            {
                var value = lt.Text;
                Console.WriteLine(value);
                selectedsites[j] = value;
                j++;
            }

        }
        var date =  DateDropdownList.SelectedValue;
        Session["sitename"] = selectedsites;
        Session["SurveyDate"] = date;
        Response.Redirect("UpdateVAtree.aspx");
    }

    protected void AreaDropDownList_SelectedIndexChanged(object sender, EventArgs e)
    {
        var clientid = Int32.Parse(AreaDropDownList .SelectedValue);
        var STA = new DataAccess.i2iPortalTableAdapters.SitesTableAdapter();
     
        DataTable st = STA.GetDataByClientID(clientid);
        SitesCheckBoxList.Items.Clear();

        foreach (DataRow site in st.Rows)
        {
            var siteName = site["siteName"].ToString();
            var siteid = site["site_id"].ToString();

            var site_CB = new CheckBox();
            site_CB.Text = siteName;
            site_CB.ID = siteid;
            SitesCheckBoxList.Items.Add(siteName);

        }
        setDateList();
    }

    protected void LoginStatus1_LoggingOut(object sender, LoginCancelEventArgs e)
    {
        Session.Contents.Remove("UserDetails");
        Session.Abandon();
        Session.Contents.RemoveAll();
        FormsAuthentication.SignOut();
        Response.Redirect("../Default.aspx");
    }
}
